import { query, operation } from '../services/testDevice';
import { isSuccess } from '../configs/error';
import createModel from './base';

export default createModel({
  namespace: 'testDevice',

  state: {
    list: [],
    isTesting: false,
    selectedRowKeys: [],
    testType: 1,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        // dispatch({
        //   type: 'query'
        // });

        if (location.pathname === '/testDevice') { // 每次刷新一下，获取最新
        	// dispatch({
        	// 	type: 'query'
        	// });
        } else {
          dispatch({
            type: 'querySuccess',
            payload: {
              isTesting: false
            },
          });
        }
      });
    },
  },

  effects: {
    *query({ payload = {}, resetSelectedRowKeys = false }, { call, put, select }) {
      const data = yield call(query, payload);
      if (data.code == 200) {
        data.data && data.data.forEach((item, index) => {
          item.index = index + 1;
        });
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(data.size) || 20,
              total: data.total,
            },
            selectedRowKeys: [],
            unitList: payload.unitList || false
          },
        });
      }
    },
    *operation({ payload = {}, }, { call, put, select }) {
      const data = yield call(operation, payload);
      if (data.code == 200) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(data.size) || 20,
              total: data.total,
            },
            selectedRowKeys: []
          },
        });
      }
    },
  },
  reducers: {
    querySuccess(state, { payload }) {
      /*
       * state.list新数据和现有数据替换
       */
      let result = result = {
        ...state,
        ...payload,
      };
      if (payload.list && !payload.unitList) {
        const stateList = [...state.list];
        const payloadList = [...payload.list];
        const oObj = {};
        // 利用imei号相同  替换最新数据
        if (stateList.length) {
          stateList.forEach((item, i) => {
            oObj[item.imei] = item;
          });
        }
        if (payloadList.length) {
          payloadList.forEach((item, i) => {
            const oIndex = oObj[item.imei].index;
            oObj[item.imei] = item;
            oObj[item.imei].index = oIndex;
          });
        }
        // oObj按index大小排序
        const finalObj = [];
        for (const key in oObj) {
          finalObj[oObj[key].index - 1] = oObj[key];
        }
        result = {
          ...state,
          ...payload,
          list: [...Object.values(finalObj)]
        };
      }
      return result;
    },
  },
}, query);
